<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;

abstract class AbstractController
{
    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected ResponseInterface $response;


    public function success($data, $message = 'OK')
    {
        return ([
            'code'=> 200,
            'success'=> true,
            'message'=> $message,
            'data' => $this->_unsetNull($data)
        ]);
    }
    public function error( $message = 'error', $code = 400)
    {
        return ([
            'code'=> $code,
            'message'=> $message,
            'success'=> false,
        ]);
    }

    /*
     * null值转为空字符串 @param array $arr
     */
    protected function _unsetNull($arr){
        if(is_object($arr))$arr = $arr->toArray();
        if($arr !== null){
            if(is_array($arr)){
                if(!empty($arr)){
                    foreach($arr as $key => $value){
                        if($value === null){
                            $arr[$key] = '';
                        }else{
                            $arr[$key] = $this->_unsetNull($value);      //递归再去执行
                        }
                    }
                }else{ $arr = []; }
            }else{
                if($arr === null){ $arr = ''; }         //注意三个等号
            }
        }else{ $arr = ''; }
        return $arr;
    }
}
